import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 模拟聊天记录
const mockChatHistory = [
  {
    id: 'C001',
    type: 'assistant',
    content: '您好！我是智慧医院AI客服助手，有什么可以帮助您的吗？',
    timestamp: new Date(Date.now() - 60000).toISOString(),
    isImage: false,
    isAudio: false
  }
]

// 异步thunk
export const fetchChatHistory = createAsyncThunk(
  'chat/fetchChatHistory',
  async () => {
    // 从localStorage获取聊天记录
    try {
      const stored = localStorage.getItem('customerServiceChatHistory')
      if (stored) {
        return JSON.parse(stored)
      }
    } catch (error) {
      console.error('Failed to parse stored chat history:', error)
    }
    return mockChatHistory
  }
)

export const sendMessage = createAsyncThunk(
  'chat/sendMessage',
  async (messageData) => {
    // 模拟AI回复
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 根据消息内容生成AI回复
    const aiReply = generateAIReply(messageData.content)
    
    return {
      userMessage: messageData,
      aiReply: {
        id: `C${Date.now()}`,
        type: 'assistant',
        content: aiReply,
        timestamp: new Date().toISOString(),
        isImage: false,
        isAudio: false
      }
    }
  }
)

export const uploadFile = createAsyncThunk(
  'chat/uploadFile',
  async (fileData) => {
    // 模拟文件上传
    await new Promise(resolve => setTimeout(resolve, 500))
    
    return {
      id: `C${Date.now()}`,
      type: 'user',
      url: URL.createObjectURL(fileData.file),
      content: fileData.file.name,
      timestamp: new Date().toISOString(),
      isImage: fileData.file.type.startsWith('image/'),
      isAudio: fileData.file.type.startsWith('audio/'),
      fileName: fileData.file.name,
      fileSize: fileData.file.size
    }
  }
)

// 生成AI回复的简单逻辑
const generateAIReply = (userMessage) => {
  const message = userMessage.toLowerCase()
  
  if (message.includes('挂号') || message.includes('预约')) {
    return '您可以通过以下方式挂号：\n1. 点击首页"门诊挂号"按钮\n2. 选择科室和医生\n3. 选择就诊时间\n4. 确认预约信息\n\n需要我为您详细说明某个步骤吗？'
  } else if (message.includes('缴费') || message.includes('支付')) {
    return '门诊缴费支持多种支付方式：\n1. 微信支付\n2. 支付宝\n3. 银行卡\n4. 医保卡\n\n您可以在"门诊缴费"页面查看待缴费项目并进行支付。'
  } else if (message.includes('报告') || message.includes('检查')) {
    return '检查报告通常在检查完成后24-48小时内出具，您可以在"门诊报告"页面查看。\n\n如有紧急情况，请直接联系相关科室。'
  } else if (message.includes('医保') || message.includes('报销')) {
    return '医保报销需要：\n1. 持有效医保卡\n2. 在医保定点医院就诊\n3. 符合医保报销范围\n\n具体报销比例请咨询医保部门。'
  } else {
    return '感谢您的咨询！如果还有其他问题，请随时告诉我。您也可以点击下方的快捷操作按钮获取相关信息。'
  }
}

// 初始状态
const initialState = {
  chatHistory: [],
  loading: false,
  error: null,
  isTyping: false
}

// 创建slice
const chatSlice = createSlice({
  name: 'chat',
  initialState,
  reducers: {
    // 添加用户消息
    addUserMessage: (state, action) => {
      state.chatHistory.push(action.payload)
      // 保存到localStorage
      try {
        localStorage.setItem('customerServiceChatHistory', JSON.stringify(state.chatHistory))
      } catch (error) {
        console.error('Failed to save chat history:', error)
      }
    },
    // 添加AI回复
    addAIReply: (state, action) => {
      state.chatHistory.push(action.payload)
      // 保存到localStorage
      try {
        localStorage.setItem('customerServiceChatHistory', JSON.stringify(state.chatHistory))
      } catch (error) {
        console.error('Failed to save chat history:', error)
      }
    },
    // 设置正在输入状态
    setTyping: (state, action) => {
      state.isTyping = action.payload
    },
    // 清除聊天记录
    clearChatHistory: (state) => {
      state.chatHistory = []
      try {
        localStorage.removeItem('customerServiceChatHistory')
      } catch (error) {
        console.error('Failed to clear chat history:', error)
      }
    },
    // 删除单条消息
    deleteMessage: (state, action) => {
      state.chatHistory = state.chatHistory.filter(
        message => message.id !== action.payload
      )
      // 保存到localStorage
      try {
        localStorage.setItem('customerServiceChatHistory', JSON.stringify(state.chatHistory))
      } catch (error) {
        console.error('Failed to save chat history:', error)
      }
    },
    // 清除错误
    clearError: (state) => {
      state.error = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取聊天记录
      .addCase(fetchChatHistory.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchChatHistory.fulfilled, (state, action) => {
        state.loading = false
        state.chatHistory = action.payload
      })
      .addCase(fetchChatHistory.rejected, (state, action) => {
        state.loading = false
        state.error = action.error.message
      })
      // 发送消息
      .addCase(sendMessage.pending, (state) => {
        state.isTyping = true
        state.error = null
      })
      .addCase(sendMessage.fulfilled, (state, action) => {
        state.isTyping = false
        // 用户消息和AI回复都会通过reducer添加
      })
      .addCase(sendMessage.rejected, (state, action) => {
        state.isTyping = false
        state.error = action.error.message
      })
      // 上传文件
      .addCase(uploadFile.fulfilled, (state, action) => {
        state.chatHistory.push(action.payload)
        // 保存到localStorage
        try {
          localStorage.setItem('customerServiceChatHistory', JSON.stringify(state.chatHistory))
        } catch (error) {
          console.error('Failed to save chat history:', error)
        }
      })
  }
})

// 导出actions
export const {
  addUserMessage,
  addAIReply,
  setTyping,
  clearChatHistory,
  deleteMessage,
  clearError
} = chatSlice.actions

// 导出selectors
export const selectChatHistory = (state) => state.chat.chatHistory
export const selectChatLoading = (state) => state.chat.loading
export const selectChatError = (state) => state.chat.error
export const selectIsTyping = (state) => state.chat.isTyping

// 导出reducer
export default chatSlice.reducer
